/**
 *    Copyright 2009 Seth Albnaese
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/** $Id: AquiferPipelineFactory.java 24 2009-05-11 13:27:21Z salbanese0080@gmail.com $ */

package org.aquiferserver.server;

import static org.jboss.netty.channel.Channels.*;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.ChannelHandler;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.handler.codec.frame.DelimiterBasedFrameDecoder;
import org.jboss.netty.handler.codec.frame.Delimiters;
import org.jboss.netty.handler.codec.string.StringDecoder;
import org.jboss.netty.handler.codec.string.StringEncoder;

/**
 * @author Seth Albanese
 * @version $Id: AquiferPipelineFactory.java 24 2009-05-11 13:27:21Z salbanese0080@gmail.com $
 */
public class AquiferPipelineFactory implements ChannelPipelineFactory {

	protected static final Log logger = LogFactory.getLog( org.aquiferserver.server.AquiferPipelineFactory.class );
	
	private final ChannelHandler handler;	
	
	public AquiferPipelineFactory ( ChannelHandler handler )
	{
		this.handler = handler;
	}
	
	/* (non-Javadoc)
	 * @see org.jboss.netty.channel.ChannelPipelineFactory#getPipeline()
	 */
	@Override
	public ChannelPipeline getPipeline() throws Exception 
	{
		logger.debug( "Generating pipeline from Factory" );
		
		ChannelPipeline pipeline = pipeline();
		
		byte delimiter = new String("|").getBytes()[0];
		
		ChannelBuffer[] decoder = new ChannelBuffer[] { ChannelBuffers.wrappedBuffer(new byte[] { delimiter }) };
		
		pipeline.addLast( "framer", new DelimiterBasedFrameDecoder ( 8129, true, decoder ) );
		pipeline.addLast( "decoder", new StringDecoder() );
		pipeline.addLast( "encoder", new StringEncoder() );
		
		pipeline.addLast( "handler", handler );
		
		logger.debug( "returning pipeline" );
		
		return pipeline;
	}

}
